<template>
    <div>
        <div class="search-term">
            <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
                <el-form-item>
                    <el-input
                            placeholder="请输入教室名称"
                            v-model="searchInfo.classRoomName"
                            clearable
                            size="small"
                    ></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="onSubmit" type="primary" size="small"
                    >搜 索
                    </el-button
                    >
                </el-form-item>
                <el-form-item>
                    <el-button @click="openDialog('add')" size="small" v-if="btns&&btns.includes('add')">新 增</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button @click="importInfo()" size="small" v-if="btns&&btns.includes('add')">导 入</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-table :data="tableData" style="width: 100%;margin-bottom: 10px;" border>
            <el-table-column prop="schoolName" label="学校名称" align="center" v-if="searchInfo.currentRoleId!==4">
            </el-table-column>
            <el-table-column prop="classRoomName" label="教室名称" align="center">
            </el-table-column>
            <el-table-column prop="classRoomCapacity" label="容量(人)" align="center">
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="200px">
                <template slot-scope="scope">
                    <el-button
                            @click="handleClassroom(scope.row)"
                            size="small"
                            type="primary"
                            icon="el-icon-edit"
                            v-if="btns&&btns.includes('edit')"
                    >编辑
                    </el-button
                    >
                    <el-button
                            @click="deleteAreas(scope.row)"
                            size="small"
                            type="danger"
                            icon="el-icon-delete"
                            v-if="btns&&btns.includes('delete')"
                    >删除
                    </el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :current-page="currPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 30, 50, 100]"
                :style="{ float: 'right', padding: '20px' }"
                :total="totalCount"
                @current-change="handlepageChange"
                @size-change="handleSizeChange"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>

        <el-dialog
                :before-close="closeDialog"
                :title="dialogTitle"
                :visible.sync="dialogFormVisible"
                class="dialogs"
                width="380px"
        >
            <el-form
                    :model="form"
                    :inline="true"
                    :rules="rules"
                    label-width="80px"
                    ref="areaForm"
            >
                <el-form-item label="教室名称" prop="classRoomName">
                    <el-input
                            autocomplete="off"
                            v-model="form.classRoomName"
                            size="small"
                            placeholder="请输入教室名称"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="容量(人)" prop="classRoomCapacity">
                    <el-input
                            autocomplete="off"
                            v-model="form.classRoomCapacity"
                            size="small"
                            placeholder="请输入容量(人)"
                            clearable
                    ></el-input>
                </el-form-item>
            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeDialog" size="small">取 消</el-button>
                <el-button @click="enterDialog" type="primary" size="small"
                >确 定
                </el-button
                >
            </div>
        </el-dialog>


        <!--导入-->
        <el-dialog
                :before-close="closeImportDialog"
                title="教室导入"
                :visible.sync="dialogImportVisible"
                class="dialogs"
                width="380px"
        >
            <div style="float: left;">
                <el-upload
                        class="upload-demo"
                        :action="`${path}/api-course/class-room/import`"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :before-upload="checkFile"
                        :on-error="uploadError"
                        :on-success="uploadSuccess"
                        :headers="{ Authorization: token,clientType: 'webApp' }"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove">
                    <el-button size="small" type="primary">选择导入文件</el-button>
                </el-upload>
            </div>
            <div style="float: left;margin-top: 8px; margin-left: 8px;">
                <el-link href="https://istudy-prod.oss-cn-hangzhou.aliyuncs.com/excel/template/教室导入.xlsx">下载模板<i
                        class="el-icon-download el-icon--right"></i>
                </el-link>
            </div>
            <div style="clear: left;margin-top: 20px;text-align: center;" slot="footer">
                <el-button @click="closeImportDialog" size="small">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    // 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成 条件搜索时候 请把条件安好后台定制的结构体字段 放到 this.searchInfo 中即可实现条件搜索
    import {mapGetters} from "vuex";
    import {addClassroom, classroomList, deleteClassroom, editClassroom, enableClassRoom} from "@/api/classroom";
    import infoList from "@/components/mixins/infoList";

    export default {
        name: "Area",
        mixins: [infoList],
        data() {
            return {
                path: process.env.VUE_APP_BASE_API,
                searchInfo: {classRoomName: '', currentAreaId: 0, currentRoleId: 0},
                btns: [],
                statusOptions: [
                    {
                        value: 0,
                        label: "否",
                    },
                    {
                        value: 1,
                        label: "是",
                    },
                ],
                roleOptions: [
                    {
                        value: 0,
                        label: "机构",
                    },
                    {
                        value: 1,
                        label: "学校",
                    },
                    {
                        value: 2,
                        label: "教育局",
                    },
                    {
                        value: 3,
                        label: "管理员",
                    },
                ],
                listApi: classroomList,
                dialogImportVisible: false,
                dialogFormVisible: false,
                dialogTitle: "新增教室",
                form: {classRoomName: '', classRoomCapacity: ''},
                type: "",
                rules: {
                    classRoomName: [
                        {required: true, message: "请输入教室名称", trigger: "blur"},
                    ],
                    classRoomCapacity: [
                        {required: true, message: "请输入容量", trigger: "blur"},
                    ]
                },
            };
        },
        computed: {
            ...mapGetters("user", ["userInfo", "token"]),
        },
        methods: {
            handleRemove(file, fileList) {
            },
            handlePreview(file) {
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            closeImportDialog() {
                this.dialogImportVisible = false;
            },
            //导入框
            importInfo() {
                this.dialogImportVisible = true;
            },
            //条件搜索前端看此方法
            onSubmit() {
                this.page = 1;
                this.pageSize = 10;
                this.getTableData();
            },
            initForm() {
                this.$refs.areaForm.resetFields();
                this.$forceUpdate();
            },
            closeDialog() {
                this.initForm();
                this.dialogFormVisible = false;
                this.getTableData();
            },
            openDialog(type) {
                switch (type) {
                    case "add":
                        this.dialogTitle = "新增教室";
                        break;
                    case "edit":
                        this.dialogTitle = "编辑教室";
                        break;
                    default:
                        break;
                }
                this.type = type;
                this.dialogFormVisible = true;
            },
            handleClassroom(row) {
                this.form = row;
                this.type = 'edit'
                this.openDialog("edit");
            },
            //启用/停用
            async changeEnable(row) {
                const res = await enableClassRoom(row.classRoomId)
                if (res.statusCode === 0) {
                    this.$message({
                        type: "success",
                        message: "启用/停用成功",
                        showClose: true,
                    });
                }
                this.getTableData();
            },
            async deleteAreas(row) {
                this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(async () => {
                        const res = await deleteClassroom(row.classRoomId);
                        if (res.statusCode === 0) {
                            this.$message({
                                type: "success",
                                message: "删除成功!",
                            });
                            this.getTableData();
                        }
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
            },
            async enterDialog() {
                this.$refs.areaForm.validate(async (valid) => {
                    if (valid) {
                        switch (this.type) {
                            case "add": {
                                // console.log(this.form)
                                const {classRoomCapacity, classRoomName, disableState} = this.form
                                const res = await addClassroom({classRoomCapacity, classRoomName, disableState});
                                if (res.statusCode === 0) {
                                    this.$message({
                                        type: "success",
                                        message: "添加成功",
                                        showClose: true,
                                    });
                                }
                                this.getTableData();
                                this.closeDialog();
                            }

                                break;
                            case "edit": {
                                const {classRoomCapacity, classRoomName, disableState, classRoomId} = this.form
                                let params = {classRoomCapacity, classRoomName, disableState, classRoomId}
                                const res = await editClassroom(params);
                                if (res.statusCode === 0) {
                                    this.$message({
                                        type: "success",
                                        message: "编辑成功",
                                        showClose: true,
                                    });
                                }
                                this.getTableData();
                                this.closeDialog();
                            }
                                break;
                            default: {
                                this.$message({
                                    type: "error",
                                    message: "未知操作",
                                    showClose: true,
                                });
                            }
                                break;
                        }
                    }
                });
            },
            //文件上传
            checkFile(file) {
                const isXls = file.type === "application/vnd.ms-excel";
                const isXlsx = file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isXls && !isXlsx) {
                    this.$message.error("文件格式错误!");
                }
                if (!isLt2M) {
                    this.$message.error("上传文件大小不能超过 2MB!");
                }
                return (isXls || isXlsx) && isLt2M;
            },
            uploadSuccess(res) {
                if (res.statusCode == 0) {
                    this.$message({
                        type: "success",
                        message: "上传成功",
                    });
                    this.dialogImportVisible = false;
                    this.getTableData();
                } else {
                    this.$message({
                        type: "warning",
                        message: res.msg,
                    });
                }
            },
            uploadError() {
                this.$message({
                    type: "error",
                    message: "上传失败",
                });
            },
        },
        filters: {
            methodFiletr(value) {
                const target = methodOptions.filter((item) => item.value === value)[0];
                // return target && `${target.label}(${target.value})`
                return target && `${target.label}`;
            },
            tagTypeFiletr(value) {
                const target = methodOptions.filter((item) => item.value === value)[0];
                return target && `${target.type}`;
            },
        },
        created() {
            this.searchInfo.currentAreaId = this.userInfo.areaId;
            this.searchInfo.currentRoleId = this.userInfo.roleId;
            this.btns = this.$route.meta.btnList
            this.getTableData();

        },
    };
</script>
<style scoped lang="scss">
    .green {
        color: #67c23a;
    }

    .red {
        color: #f56c6c;
    }

    .button-box {
        // padding: 10px 20px;
        .el-button {
            float: right;
        }
    }

    .el-tag--mini {
        margin-left: 5px;
    }

    .dialogs {
        ::v-deep .el-input__inner {
            width: 225px;
        }

        .dialog-footer {
            text-align: center;
        }

        ::v-deep .el-input-number .el-input__inner {
            width: 130px;
        }
    }

    ::v-deep .el-upload-list__item-status-label {
        right: 0;
        left: 300px;
    }
</style>
